﻿using System;
using System.Collections.Generic;
using System.Linq;

using NTQOnlineExam.Services.EntityFW.Repository;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;
using NTQOnlineExam.Services.ReportService.Account;
using NTQOnlineExam.Services.ReportService.Basket;

namespace NTQOnlineExam.Services.ReportService.Portfolio
{
    public class PortfolioReportService : IPortfolioReportService
    {
        private readonly IGenericRepository<EntityFW.Entity.Portfolio> _portfolioRepository;
        private readonly IAccountReportService _accountReportService;
        private readonly IBasketReportService _basketReportService;
        private readonly ICommandExecutor _executor;
        public PortfolioReportService(IGenericRepository<EntityFW.Entity.Portfolio> portfolioRepository, IAccountReportService accountReportService, IBasketReportService basketReportService, ICommandExecutor executor)
        {
            _portfolioRepository = portfolioRepository;
            _accountReportService = accountReportService;
            _basketReportService = basketReportService;
            _executor = executor;
        }

        public bool ValidateCurrentBasket()
        {
            var basket = _basketReportService.GetCurrentBasket();
            if (basket == null || basket.BasketItems == null || !basket.BasketItems.Any()) return false;
            int total;
            var currentUserPortfolio = GetCurrentUserActivePortfolio(new SearchCriteria.SearchCriteria() { Keyword = string.Empty }, true, 0, int.MaxValue, out total);
            return currentUserPortfolio.All(portfolioDto => basket.BasketItems.All(x => x.TermId != portfolioDto.TermId));
        }

        public bool CheckTermNotInPortfolio(int termId)
        {
            int total;
            var currentUserPortfolio = GetCurrentUserActivePortfolio(new SearchCriteria.SearchCriteria() { Keyword = string.Empty }, true, 0, int.MaxValue, out total);
            return currentUserPortfolio.All(portfolioDto => termId != portfolioDto.TermId);
        }

        public IList<PortfolioDTO> GetCurrentUserActivePortfolio(SearchCriteria.SearchCriteria criteria, bool includeUnPublishedTerm, int pageIndex, int pageSize, out int total)
        {
            var user = _accountReportService.GetCurrentUser();
            total = 0;
            if (user == null) return new List<PortfolioDTO>();
            var result = _executor.Execute(new GetUserActivePortfolioDbCommand(includeUnPublishedTerm, criteria, (int)user.ProviderUserKey, pageSize, pageIndex));
            if (result == null)
            {
                total = 0;
                return new List<PortfolioDTO>();
            }
            total = result.Count;
            return result.Items;
        }
    }
}
